const express = require('express')
const cors = require('cors')
const bodyParser = require('body-parser')
const Joi = require('joi')

const app = express()
const port = 3000

app.use(cors())
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
app.use((req, res, next) => {
  res.reqError = (err, status = 500) => {
    res.send({
      status,
      message: err instanceof Error ? err.message : err,
    })
  }
  res.reqSuc = (info, status = 200) => {
    res.send({
      status,
      message: info instanceof Success ? info.message : info,
    })
  }
  next()
})

const jwtConfig = require('./jwt-config/index')
const { expressjwt: jwt } = require('express-jwt')
app.use(
  jwt({
    secret: jwtConfig.jwtSecretKey,
    algorithms: ['HS256'],
  }).unless({
    path: [/^\/api\//],
  }),
)

const loginRouter = require('./router/login')
app.use('/api', loginRouter)
app.use(err => {
  if (err instanceof Joi.ValidationError) return res.reqError(err)
})

app.listen(port, () => {
  console.info(`http://127.0.0.1:${port}`)
})
